package com.poisonh.unifiedauth.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dialog.AddCardListPopWindow;
import com.poisonh.unifiedauth.dialog.CardDialogFragment;
import com.poisonh.unifiedauth.identitysliding.ShadowTransformer;
import com.poisonh.unifiedauth.identitysliding.ViewPager;
import com.poisonh.unifiedauth.identitysliding.adapter.CardPagerAdapter;
import com.poisonh.unifiedauth.model.BusinessCard;
import com.poisonh.unifiedauth.model.IdCard;
import com.poisonh.unifiedauth.ui.fragment.BusinuessCardFragment;
import com.poisonh.unifiedauth.ui.fragment.IdCardFragment;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utilLib.listener.OnOperItemClickL;
import com.poisonh.unifiedauth.utilLib.widget.ActionSheetDialog;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.GlideCircleTransform;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;

/**
 * 消息中心
 * 身份认证图片滑动的界面
 * Created by PoisonH on 2016/7/11.
 */
public class IdentityCardActivity extends BaseActivity implements View.OnClickListener,AddCardListPopWindow.OnClickTypeListener,BusinuessCardFragment.OnClickFramgmentItemListener,CardDialogFragment.CardStatuChangeEventListener
{

    private List<Fragment> mFragments = new ArrayList<Fragment>();

    /**
     * idcard:1
     */
    private List<Integer> types = new ArrayList<Integer>();

    public static final int TYPE_NONE = 0;
    public static final int TYPE_IDCARD = 1;//身份更新成标记
    private ArrayList<CardView> mlist=new ArrayList<>();
    private ViewPager mViewPager;
    private CardPagerAdapter mCardAdapter;
    private ShadowTransformer mCardShadowTransformer;

    private float mAlplaNum;
    private float mScaleNum;


    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_identity_card);

        initTitleView();
        initView();
       // initLintener();
       // loadData();
    }

    @Override
    protected void initView()
    {
        mRightBtn.setVisibility(View.GONE);
        mTvTitle.setText("身份管理");
        mTvRight.setText("添加");
        mTvRight.setVisibility(View.VISIBLE);

        mLeftBtn.setOnClickListener(this);
        mTvRight.setOnClickListener(this);


//        mOrientedViewPager = (OrientedViewPager) findViewById(R.id.view_pager);
//
//        //设置viewpager的方向为竖直
//        mOrientedViewPager.setOrientation(OrientedViewPager.Orientation.VERTICAL);
//        //设置幕后item的缓存数目
//        mOrientedViewPager.setOffscreenPageLimit(4);
//        //设置transformer
//        mOrientedViewPager.setPageTransformer(true, new VerticalStackTransformer(getApplicationContext()));
        mViewPager=(ViewPager)findViewById(R.id.viewPager);
       // initData();
//        mCardShadowTransformer = new ShadowTransformer(mViewPager, mCardAdapter);
//        mViewPager.setPageTransformer(false, mCardShadowTransformer);
//        mViewPager.setOffscreenPageLimit(4);
        initData();

    }

    /**
     * 初始化数据
     */
    private void initData() {

        mlist.clear();
        types.clear();

        Realm realm = Realm.getDefaultInstance();
        IdCard idCard = realm.where(IdCard.class).equalTo("uid", mStrUserId).findFirst();
//
        if(idCard!=null){
            CardView cardView_idcard= (CardView) LayoutInflater.from(this).inflate(R.layout.item_id_card,null);
            ImageView ivHeadImg = (ImageView)cardView_idcard.findViewById(R.id.iv_id_card_head_img);
            Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL +idCard.getHeadImg()).into(ivHeadImg);

            TextView tvName = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_name);
            TextView tvSex = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_sex);
            TextView tvFamilyName = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_family_name);
            TextView tvYear = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_year);
            TextView tvMonth = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_month);
            TextView tvDay = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_day);
            TextView tvAddress = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_address);
            TextView tvIdNumber = (TextView)cardView_idcard.findViewById(R.id.tv_id_card_id_number);

            tvName.setText(idCard.getName());
            tvSex.setText(idCard.getSex());
            tvFamilyName.setText(idCard.getFamilyName());

            try {
                String birth = idCard.getBirth();
                String[] ss = birth.split("-");
                if (ss.length == 3) ;
                {
                    tvYear.setText(ss[0]);
                    tvMonth.setText(ss[1]);
                    tvDay.setText(ss[2].substring(0,2));
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
            // tvAddress.setText(idCard.getAddress());
            tvAddress.setText(idCard.getAddress());
            tvIdNumber.setText(idCard.getIdNumber());
            mlist.add(cardView_idcard);
        }else {
            types.add(TYPE_IDCARD);
        }

        if(types.size()==0){
            types.add(TYPE_NONE);
        }






        BusinessCard mBusinessCard = realm.where(BusinessCard.class).equalTo("uid", mStrUserId).findFirst();


        if(mBusinessCard!=null){
            CardView cardView_busnesscard= (CardView) LayoutInflater.from(this).inflate(R.layout.item_fancycoverflow,null);
            TextView mName = (TextView) cardView_busnesscard.findViewById(R.id.name);
            TextView mCellphone = (TextView) cardView_busnesscard.findViewById(R.id.cellphone);
            TextView mEMail = (TextView) cardView_busnesscard.findViewById(R.id.email);
            TextView mCompany = (TextView) cardView_busnesscard.findViewById(R.id.company);
            ImageView mMyHead = (ImageView) cardView_busnesscard.findViewById(R.id.head_img);

            ImageView  mCellphoneImg = (ImageView) cardView_busnesscard.findViewById(R.id.cellphone_img);
            ImageView  mEMailImg = (ImageView) cardView_busnesscard.findViewById(R.id.email_img);
            ImageView   mCompanyImg = (ImageView) cardView_busnesscard.findViewById(R.id.company_img);


            mName.setText(mBusinessCard.getName());
            mCellphone.setText(mBusinessCard.getMobile());
            mEMail.setText(mBusinessCard.getEmail());
            mCompany.setText(mBusinessCard.getCompany());

            String strMobile = mBusinessCard.getMobile();
            if(strMobile==null||"".equals(strMobile)){
                mCellphoneImg.setVisibility(View.INVISIBLE);
                mCellphone.setText("");
            }else{
                mCellphoneImg.setVisibility(View.VISIBLE);
                mCellphone.setText(strMobile);
            }

            String strEmail = mBusinessCard.getEmail();
            if(strEmail==null||"".equals(strEmail)){
                mEMailImg.setVisibility(View.INVISIBLE);
                mEMail.setText("");
            }else{
                mEMailImg.setVisibility(View.VISIBLE);
                mEMail.setText(strEmail);

            }

            String strCompany = mBusinessCard.getCompany();
            if(strCompany==null||"".equals(strCompany)){
                mCompanyImg.setVisibility(View.INVISIBLE);
                mCompany.setText("");
            }else{
                mCompanyImg.setVisibility(View.VISIBLE);
                mCompany.setText(strCompany);
            }

            // Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL +mBusinessCard.getHeadImg()).into(mMyHead);
            Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL+ mBusinessCard.getHeadImg()).transform(new GlideCircleTransform(this)).into(mMyHead);
            mlist.add(cardView_busnesscard);
        }


        mCardAdapter = new CardPagerAdapter(this,mlist);
        mViewPager.setAdapter(mCardAdapter);
        mCardShadowTransformer = new ShadowTransformer(mViewPager, mCardAdapter);
        mViewPager.setPageTransformer(false, mCardShadowTransformer);
        mViewPager.setOffscreenPageLimit(4);
        mCardAdapter.setOnItemClickListener(new CardPagerAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                mViewPager.setCurrentItem(position);
             //   Toast.makeText(IdentityCardActivity.this, "点击成功", Toast.LENGTH_SHORT).show();
                if(position==0){

                }else if(position==1){
                onClickFramgmentItem();
                }
            }
        });
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ib_left_btn:
                finish();
                break;
            case R.id.tv_right_txt:

               getFragmentManager();
                showPopupWindow();
                break;


        }
    }



    @Override
    public void onClickType(Integer type)
    {
        switch (type)
        {
            case 1:
                startActivityForResult(new Intent(this, IdCardSettingActivity.class),TYPE_IDCARD);
                break;

        }

    }

    /**
     * 打开新增列表
     */
    private void showPopupWindow()
    {
        AddCardListPopWindow dddCardListPopWindow = new AddCardListPopWindow(this,types);
        dddCardListPopWindow.showPopupWindow(mTvRight);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // 根据上面发送过去的请求吗来区别
        switch (requestCode) {
            case TYPE_IDCARD:
                handlResult(data);
                break;
            default:
                break;
        }
    }

    private void handlResult(Intent data) {
        if(data!=null){
            if(data.hasExtra("result")){
                String  result  = data.getStringExtra("result");
                if("seccuss".equals(result)){
                   // loadData();
                    initData();
                }
            }

        }
    }




    private void initLintener() {

//        mCardShadowTransformer.setCanAlpha(true);
//        mCardShadowTransformer.setCanScale(true);
//
//        mAlplaNum = 1 - (float) ((100 / 100f) * 0.6 + 0.1f);//阴影比例100最大
//        mCardShadowTransformer.setAlpha(mAlplaNum, true);
//
//        mScaleNum = (float) ((50 / 100f) * 0.5);//值写为50  缩放比例
//        mCardShadowTransformer.setScale(mScaleNum, true);
//        mCardAdapter.setOnItemClickListener(new CardPagerAdapter.OnItemClickListener() {
//            @Override
//            public void onClick(int position) {
//                mViewPager.setCurrentItem(position);
//             //   Toast.makeText(IdentityCardActivity.this, "点击成功", Toast.LENGTH_SHORT).show();
//                if(position==0){
//
//                }else if(position==1){
//                onClickFramgmentItem();
//                }
//            }
//        });
    }



    /**
     * 加载数据 处理可以添加的下拉列表
     *
     */
    private void loadData(){

        mFragments.clear();
        types.clear();



        Realm realm = Realm.getDefaultInstance();


        IdCard idCard = realm.where(IdCard.class).equalTo("uid", mStrUserId).findFirst();

        if(idCard!=null){
            mFragments.add(new IdCardFragment(idCard));
        }else {
            types.add(TYPE_IDCARD);
        }

        if(types.size()==0){
            types.add(TYPE_NONE);
        }

        BusinessCard businessCard = realm.where(BusinessCard.class).equalTo("uid", mStrUserId).findFirst();
        //制造数据

        if(businessCard!=null){
            mFragments.add(new BusinuessCardFragment(businessCard));
        }

//        mContentFragmentAdapter = new
//                ContentFragmentAdapter(getSupportFragmentManager(), mFragments);
//
//        mOrientedViewPager.setAdapter(mContentFragmentAdapter);
    }



    @Override
    public void onClickFramgmentItem() {

//        CardDialogFragment fragment = new CardDialogFragment();
//        fragment.show(getFragmentManager(), "");
        final String[] stringItems = {"修改", "删除"};
        final ActionSheetDialog dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false).show();

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position){

                    case 0:
                        showEditEvent();
                        dialog.dismiss();
                        break;
                    case 1:
                        deleteCard();
                        dialog.dismiss();
                        break;
                }
            }
        });
    }

    @Override
    public void showEditEvent() {
        startActivityForResult(new Intent(this, SettingCardActivity.class),TYPE_IDCARD);

    }

    @Override
    public void deleteEvent() {
       // loadData();
        initData();

    }

    /**
     * 删除明信片
     */
    private void deleteCard()
    {

        SVProgressHUD.showWithStatus(IdentityCardActivity.this, "加载中...");
        HttpParams params = new HttpParams();
        //  String mStrUserId = PreferencesUtils.getString(getActivity(), "ID");
        params.put("userId", mStrUserId);
        params.put("token", mStrUserToken);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.DELETEBUSINESS, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                Realm realm = Realm.getDefaultInstance();
                realm.beginTransaction();
                realm.delete(BusinessCard.class);
                realm.commitTransaction();
                realm.close();

                ToastUtils.showToast(IdentityCardActivity.this, "删除数据成功");
                SVProgressHUD.dismiss(IdentityCardActivity.this);
                deleteEvent();
            }

            @Override
            public void onFailure(String failReason)
            {

                ToastUtils.showToast(IdentityCardActivity.this, "删除数据失败");
                SVProgressHUD.dismiss(IdentityCardActivity.this);
            }
        });
    }
}
